package com.gitee.suveng.springboot.reflect.task.config;

import java.util.EnumSet;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;

/**
 * @author suwenguang
 * @since 2021-05-25 13:57
 */
@Configuration
@EnableStateMachine
//@EnableStateMachineFactory
public class StringStateMachineConfig
	extends StateMachineConfigurerAdapter<String, String> {

	@Override
	public void configure(StateMachineConfigurationConfigurer<String, String> config)
		throws Exception {
		config
			.withConfiguration()
			.autoStartup(true)
			.listener(listenerString());
	}

	@Override
	public void configure(StateMachineStateConfigurer<String, String> states)
		throws Exception {
		EnumSet<States> objects = EnumSet.allOf(States.class);
		Set<String> collect = objects.stream().map(Enum::name).collect(Collectors.toSet());
		states
			.withStates()
			.initial(States.SI.name())
			.states(collect);
	}

	@Override
	public void configure(StateMachineTransitionConfigurer<String, String> transitions)
		throws Exception {
		transitions
			.withExternal()
			.source(States.SI.name()).target(States.S1.name()).event(Events.E1.name())
			.and()
			.withExternal()
			.source(States.S1.name()).target(States.S2.name()).event(Events.E2.name());
	}

	@Bean(name = "listenerString")
	public StateMachineListener<String, String> listenerString() {
		return new StateMachineListenerAdapter<String, String>() {
			@Override
			public void stateChanged(State<String, String> from, State<String, String> to) {
				System.out.println("State change to " + to.getId());
			}
		};
	}
}



